package project.dzz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import project.dzz.manager.response.*;
import project.dzz.mapper.MESMapper;
import project.dzz.pojo.*;
import project.dzz.pojo.Math.VarianceAndStandardDiviation;
import project.dzz.pojo.base.ProductData;

import javax.validation.constraints.Min;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务类
 * 耗时一些操作
 */
@Service
public class MESService {


    //数据库操作
    private MESMapper mesMapperl;

    @Autowired
    public MESService(MESMapper mesMapperl) {
        this.mesMapperl = mesMapperl;
    }

    /**
     * 下达任务
     */
    public int addTask(String taskStyle, String batch, int productlineNum, int planQuantity,
                       String remark, int taskStatus) {
        int code = 1;
        try {
            Task task = new Task();
            if (!StringUtils.isEmpty(taskStyle)) //如果不为空
                task.taskStyle = taskStyle;
            if (!StringUtils.isEmpty(batch))
                task.batch = batch;
            task.productlineNum = productlineNum;
            task.planQuantity = planQuantity;
            task.releaseTime = LocalDateTime.now().toString();
            if (!StringUtils.isEmpty(remark))
                task.remark = remark;
            task.taskStatus = taskStatus;
            int code1 = mesMapperl.addTask(task);
            if (code1 == 1) {
                code = 0;
            }
            return code;
        } catch (Exception e) {
            return code;
        }

    }

    /**
     * 删除任务
     */
    public int delTask(String taskStyle, String batch, Integer productlineNum) {
        int code = 1;
        try {
            Task task = new Task();
            if (!StringUtils.isEmpty(taskStyle)) //如果不为空
                task.taskStyle = taskStyle;
            if (!StringUtils.isEmpty(batch))
                task.batch = batch;
            task.productlineNum = productlineNum;
            int code1 = mesMapperl.delTask(task);
            if (code1 > 0) {
                code = 0;
            }
            return code;
        } catch (Exception e) {
            e.printStackTrace();
            return code;
        }
    }

    /**
     * 加载任务
     */
    public GetTaskResponse getTask() {
        GetTaskResponse getTaskResponse = new GetTaskResponse(1, 0);
        try {
            List<TaskInfo> taskInfos = mesMapperl.getTask();
            if (taskInfos != null && taskInfos.size() > 0) {
                for (int i = 0; i < taskInfos.size(); i++) {
                    TaskInfo taskInfo = new TaskInfo();
                    taskInfo.taskStyle = taskInfos.get(i).taskStyle;
                    taskInfo.batch = taskInfos.get(i).batch;
                    taskInfo.productlineNum = taskInfos.get(i).productlineNum;
                    taskInfo.planQuantity = taskInfos.get(i).planQuantity;
                    taskInfo.remark = taskInfos.get(i).remark;
                    taskInfo.taskStatus = taskInfos.get(i).taskStatus;
                    getTaskResponse.data.add(taskInfo);
                }
            }
            getTaskResponse.code = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getTaskResponse;
    }

    /**
     * 完成任务
     */
    public TaskResponse comTask(String taskStyle, String batch, Integer productlineNum) {
        TaskResponse taskResponse = new TaskResponse(1, 0);
        try {
            int count = mesMapperl.comTask(taskStyle, batch, productlineNum);
            if (count > 0) {
                taskResponse.code = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return taskResponse;
    }

    /**
     * 获取工序名及对应的参数名
     */
    public ParaResponse getParaName() {
        ParaResponse paraResponse = new ParaResponse(1, 0);
        try {
            //获取所有工序
            List<ProcessConfig> processConfigs = mesMapperl.getProcessConfig();

            //如果工序表不为空
            if (processConfigs != null && processConfigs.size() > 0) {
                //遍历工序表
                for (int i = 0; i < processConfigs.size(); i++) {
                    ProcessParam processParam = new ProcessParam();
                    //赋值工序名字
                    processParam.processName = processConfigs.get(i).processName;
                    //将工序id作为值拿去查询参数配置
                    processParam.parameterName = mesMapperl.getParaName(processConfigs.get(i).processId);
                    paraResponse.data.add(processParam);
                }
                paraResponse.code = 0;
                paraResponse.count = processConfigs.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paraResponse;
    }

    /**
     * 获取部件名
     */
    public CompResponse getComName() {
        CompResponse compResponse = new CompResponse(1, 0);
        try {
            List<ProcessConfig> processConfigs = mesMapperl.getProcessConfig();
            if (processConfigs != null && processConfigs.size() > 0) {
                for (int i = 0; i < processConfigs.size(); i++) {
                    compResponse.data.add(processConfigs.get(i).processName);
                }
                compResponse.code = 0;
                compResponse.count = processConfigs.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return compResponse;
    }

    /**
     * 获取工序名及其部件名以及对应的生产参数
     */
    public DataResponse getProInfo(String productcode) {
        DataResponse dataResponse = new DataResponse(1, 0);
        try {
            List<ProcessConfig> processConfigs = mesMapperl.getprocessName(productcode);
            List<CompConfig> compConfigs = mesMapperl.getCompNames(productcode);
            ProductData productData = new ProductData();
            String batch = mesMapperl.getBatch(productcode);
            if (batch != null) {
                productData.batch = batch;
            }
            if (processConfigs != null && processConfigs.size() > 0) {
                for (int i = 0; i < processConfigs.size(); i++) {
                    ProductInfo productInfo = new ProductInfo();
                    productInfo.processName = processConfigs.get(i).processName;
                    productInfo.children = mesMapperl.getparaValue(productcode, processConfigs.get(i).processId);
                    productData.proInfo.add(productInfo);
                    //dataResponse.data = productData;
                }
                if (compConfigs != null && compConfigs.size() > 0) {
                    for (int j = 0; j < compConfigs.size(); j++) {
                        //ProductData productData = new ProductData();
                        CompInfo compInfo = new CompInfo();
                        compInfo.componentName = compConfigs.get(j).componentName;
                        compInfo.batch = mesMapperl.getcompBatch(productcode, compConfigs.get(j).componentId);
                        productData.componInfo.add(compInfo);
                    }
                }
                dataResponse.code = 0;
                dataResponse.data = productData;
                dataResponse.count = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataResponse;
    }


    /**
     * 获取不合格个数及条码
     */
    public FailedResponse getBadPro(String processName, Integer productlineNum, String startTime, String endTime, Integer deviceNum, String batch, Integer stationNum, String employeeCode) {
        FailedResponse failedResponse = new FailedResponse(0, 0);
        try {
            if(batch==""){
                batch=null;
            }
            if(employeeCode==""){
                employeeCode=null;
            }
            Integer processId = mesMapperl.getProcessId(processName);
            List<String> failedProductList = mesMapperl.getFailedInfo(processId, productlineNum, startTime, endTime, deviceNum, batch, stationNum, employeeCode);
            BadProductCode badProductCode = new BadProductCode();
            badProductCode.badCount = failedProductList.size();
            if (failedProductList != null && failedProductList.size() > 0) {
                for (int i = 0; i < failedProductList.size(); i++) {
                    badProductCode.badProductCode.add(failedProductList.get(i));
                }
            }
            failedResponse.data = badProductCode;
            failedResponse.code = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return failedResponse;
    }

    public ProcessResponse getProcess() {
        ProcessResponse processResponse = new ProcessResponse(0, 0);
        try {
            List<ProcessConfig> processConfigs = mesMapperl.getProcessConfig();
            if (processConfigs != null && processConfigs.size() > 0) {
                for (int i = 0; i < processConfigs.size(); i++) {
                    processResponse.data.add(processConfigs.get(i).processName);
                }
                processResponse.count = processConfigs.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return processResponse;
    }

    public ReportResponse getProducts(String processName, String startTime, String endTime, String batch, Integer productlineNum) {
        ReportResponse reportResponse = new ReportResponse(1, 0);
        try {
            if(batch==""){
                batch=null;
            }
            String[] processname = processName.split(",");
            if (processname.length > 0) {
                for (int i = 0; i < processname.length; i++) {
                    ProductReport productReport = new ProductReport();
                    ChildrenReport childrenReport = new ChildrenReport();
                    productReport.processName = processname[i];
                    Integer processId = mesMapperl.getProcessId(processname[i]);
                    if (!StringUtils.isEmpty(batch))
                        childrenReport.batch = batch;
                    childrenReport.productionTime = mesMapperl.getproductReport(processId, startTime, endTime, batch, productlineNum).get(0).productionTime;
                    childrenReport.productCount = mesMapperl.getproductReport(processId, startTime, endTime, batch, productlineNum).get(0).productCount;
                    childrenReport.productBadCount = mesMapperl.getproductReport(processId, startTime, endTime, batch, productlineNum).get(0).productBadCount;
                    productReport.children.add(childrenReport);
                    reportResponse.data.add(productReport);
                    reportResponse.code = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reportResponse;
    }

    public EmployeeResponse getEmpInfos(String employeeCode) {
        EmployeeResponse employeeResponse = new EmployeeResponse(1, 0);
        try {
            List<ProcessConfig> processConfigs = mesMapperl.getProcessConfig();
            EmployeeInfo employeeInfo = new EmployeeInfo();
            employeeInfo.employeeCode = employeeCode;
            if (processConfigs != null && processConfigs.size() > 0) {
                for (int i = 0; i < processConfigs.size(); i++) {
                    EmployeeList employeeList = new EmployeeList();
                    employeeList.processName = processConfigs.get(i).processName;
                    employeeList.productCount = mesMapperl.getEmployeeInfo(employeeCode, processConfigs.get(i).processId);
                    employeeInfo.employeeInfo.add(employeeList);
                }
                employeeResponse.data = employeeInfo;
                employeeResponse.code = 0;
                employeeResponse.count = processConfigs.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return employeeResponse;
    }

    public AndonResponse getAndonStatus() {
        AndonResponse andonResponse = new AndonResponse(1, 0);
        try {
            andonResponse.count = mesMapperl.getAndoncount();
            andonResponse.code = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return andonResponse;
    }

    public AndonEventResponse getAanEvents() {
        AndonEventResponse andonEventResponse = new AndonEventResponse(1, 0);
        try {
            List<AndonEvent> andonEvent = mesMapperl.getAndonEvent();
            if (andonEvent != null && andonEvent.size() > 0) {
                for (int i = 0; i < andonEvent.size(); i++) {
                    andonEventResponse.data.add(andonEvent.get(i));
                }
                andonEventResponse.code = 0;
                andonEventResponse.count = andonEvent.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return andonEventResponse;
    }

    public AndonResponse doAanEvenCom(String contact, String tel, String contactContent, String remark, String startTime, int andonStyle) {
        AndonResponse andonResponse = new AndonResponse(1, 0);
        try {
            FinishAndon finishAndon = new FinishAndon();
            if (!StringUtils.isEmpty(contact)) {
                finishAndon.contact = contact;
            }
            if (!StringUtils.isEmpty(tel)) {
                finishAndon.tel = tel;
            }
            if (!StringUtils.isEmpty(contactContent)) {
                finishAndon.contactContent = contactContent;
            }
            if (!StringUtils.isEmpty(remark)) {
                finishAndon.remark = remark;
            }
            finishAndon.endTime = LocalDateTime.now().toString();
            int count = mesMapperl.fininshAndon(finishAndon.contact, finishAndon.tel, finishAndon.contactContent, finishAndon.endTime, finishAndon.remark, andonStyle, startTime);
            if (count > 0) {
                andonResponse.code = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return andonResponse;
    }

    /**
     * 系统参数配置
     */
    public int processid;
    public int parameterid;
    public int componentid;
    public int propara;
    public int procomp;
    SysSetResponse sysSetResponse = new SysSetResponse(1, 0);
    public SysSetResponse doSysSettings(String processName, Integer processId, String parameterName, Integer parameterId, String componentName, Integer componentId) {

        try {
            processid = mesMapperl.processId(processId,processName);
            parameterid = mesMapperl.parameterId(parameterId, parameterName);
            componentid = mesMapperl.componentId(componentId, componentName);
            propara = mesMapperl.proPara(parameterId);
            procomp = mesMapperl.proComp(componentId);
            //如果该工序配置信息存在，则添加参数和部件配置
            if (processid > 0) {
                SysSettings(processName, processId, parameterName, parameterId, componentName, componentId);
            } else {
                int count1 = mesMapperl.addProcess(processId, processName);
                if (count1 > 0) {
                    SysSettings(processName, processId, parameterName, parameterId, componentName, componentId);
                    sysSetResponse.code = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sysSetResponse;
    }

    public void SysSettings(String processName, Integer processId, String parameterName, Integer parameterId, String componentName, Integer componentId) {
        //该参数配置不存在，部件配置存在
        //部件配置不存在，参数配置存在
        //参数配置部件配置都不存在
        if (!StringUtils.isEmpty(parameterId) && (!StringUtils.isEmpty(parameterName))) {
            if (parameterid == 0) {
                int count1 = mesMapperl.addProPara(processId, parameterId);
                int count2 = mesMapperl.addPara(parameterId, parameterName);
                if (count1 > 0 && count2 > 0) {
                    sysSetResponse.code = 0;
                }
            }
        }
        if (!StringUtils.isEmpty(componentId) && (!StringUtils.isEmpty(componentName))) {
            if (componentid == 0) {
                int count3 = mesMapperl.addProComp(processId, componentId);
                int count4 = mesMapperl.addComp(componentId, componentName);
                if (count3 > 0 && count4 > 0) {
                    sysSetResponse.code = 0;
                }
            }
        }
        if (!StringUtils.isEmpty(parameterId) && (!StringUtils.isEmpty(parameterName)) && (!StringUtils.isEmpty(componentId)) && (!StringUtils.isEmpty(componentName))) {
            if (parameterid == 0 && componentid == 0) {
                int count1 = mesMapperl.addProPara(processId, parameterId);
                int count2 = mesMapperl.addPara(parameterId, parameterName);
                int count3 = mesMapperl.addProComp(processId, componentId);
                int count4 = mesMapperl.addComp(componentId, componentName);
                if (count1 > 0 && count2 > 0 && count3 > 0 && count4 > 0) {
                    sysSetResponse.code = 0;
                }
            }
        }
    }

    public SysGetResponse getSysSettings() {
        SysGetResponse sysGetResponse = new SysGetResponse(1, 0);
        try {
            List<ProcessConfig> processConfigs = mesMapperl.getProcessConfig();
            if (processConfigs != null && processConfigs.size() > 0) {
                for (int i = 0; i < processConfigs.size(); i++) {
                    SystemGetting systemGetting = new SystemGetting();
                    systemGetting.processName = processConfigs.get(i).processName;
                    systemGetting.processId = processConfigs.get(i).processId;
                    systemGetting.paramChildren = mesMapperl.getParachildren(processConfigs.get(i).processId);
                    systemGetting.componChildren = mesMapperl.getCompchildren(processConfigs.get(i).processId);
                    sysGetResponse.data.add(systemGetting);
                }

                sysGetResponse.code = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sysGetResponse;
    }

    public ElectResponse getElect() {
        ElectResponse electResponse = new ElectResponse(1, 0);
        try {
            List<ProcessConfig> processConfigs=mesMapperl.getProcessConfig();
            for (int i = 0; i < processConfigs.size(); i++) {
                Elect elect = new Elect();
                int processid = processConfigs.get(i).processId;
                elect.processName = processConfigs.get(i).processName;
                elect.deviceNum = 1;
                elect.andonStatus = mesMapperl.getElectInfo(processid).get(0).andonStatus;
                elect.batch = mesMapperl.getElectInfo(processid).get(0).batch;
                elect.productCount = mesMapperl.getElectInfo(processid).get(0).productCount;
                elect.productBadCount = mesMapperl.getElectInfo(processid).get(0).productBadCount;
                electResponse.data.add(elect);
                electResponse.code = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return electResponse;
    }

    public CpResponse getResult(String parameterName,Integer count,String batch,Double usl,Double lsl,Integer productlineNum,Integer deviceNum,Integer stationNum){
        CpResponse cpResponse=new CpResponse(1,0);
        try {
            CpCpk cpCpk=new CpCpk();
            Integer parameterId=mesMapperl.getparameterId(parameterName);
            List<Double> value=mesMapperl.getValue(parameterId,count,batch,productlineNum,deviceNum,stationNum);
            Double std=VarianceAndStandardDiviation.Variance(value);
            cpCpk.cp=(usl-lsl)/(6*std);
            double mean=VarianceAndStandardDiviation.Mean(value);
            double cpl=Math.abs(lsl-mean)/(3*std);
            double cpu=Math.abs(usl-mean)/(3*std);
            cpCpk.cpk= Math.min(cpl,cpu);
            cpResponse.data=cpCpk;
            cpResponse.code=0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return cpResponse;
    }
}
